package com.leo.platform.shop.service.probrand.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

import com.leo.platform.server.BaseServiceImpl;
import com.leo.platform.shop.dao.ProBrandDao;
import com.leo.platform.shop.entity.probrand.ProBrand;
import com.leo.platform.shop.service.probrand.ProBrandService;

public class ProBrandServiceImpl extends BaseServiceImpl<ProBrand, Long> implements ProBrandService {

    @Autowired
    @Qualifier("proBrandDaoImpl")
    private ProBrandDao proBrandDao;

    @Override
    public void afterConstruct() {
        super.setBaseDao(proBrandDao);
    }

    /**
     * 品牌新增
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBrand(ProBrand proBrand, List<Long> categoryIds) {
        // 新增品牌信息
        proBrandDao.insertSelective(proBrand);
        // 新增品牌和分类中间表,一个品牌可能属于多个类目，所以此处是一个List categoryIds
        for (Long cid : categoryIds) {
            proBrandDao.insertCategoryBrand(cid, proBrand.getCode());
        }
    }

    /**
     * 品牌更新
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBrand(ProBrand proBrand, List<Long> categoryIds) {
        // 删除原来的数据
        deleteByBrandIdInCategoryBrand(proBrand.getCode());

        // 修改品牌信息
        proBrandDao.updateByPrimaryKeySelective(proBrand);

        // 维护品牌和分类中间表
        for (Long cid : categoryIds) {
            proBrandDao.insertCategoryBrand(cid, proBrand.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBrand(String proBrandCode, Long proBrandId) {
        // 删除品牌信息
        proBrandDao.deleteByPrimaryKey(proBrandId);

        // 维护中间表
        proBrandDao.deleteByBrandCodeInCategoryRef(proBrandCode);
    }

    /**
     * 删除中间表中的数据
     */
    @Override
    public void deleteByBrandIdInCategoryBrand(String proBrandCode) {
        proBrandDao.deleteByBrandCodeInCategoryRef(proBrandCode);
    }

    /**
     * 根据category id查询brand
     */
    @Override
    public List<ProBrand> queryBrandByCategoryId(Long categoryId) {

        return proBrandDao.queryBrandByCategoryId(categoryId);
    }

    /**
     * 根据品牌id集合查询品牌信息
     */
    @Override
    public List<ProBrand> queryBrandByBrandIds(List<Long> ids) {
        return proBrandDao.selectByIdList(ids);
    }

}
